//Powered By 66km team MakeCode 
package com.weifangfirecontrolformal.weifangfirecontrolformal.web.web.other;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.weifangfirecontrolformal.weifangfirecontrolformal.common.base.BaseController;
import com.weifangfirecontrolformal.weifangfirecontrolformal.common.utils.appkit.ConfigKit;
import com.weifangfirecontrolformal.weifangfirecontrolformal.support.annotaion.Action;
import com.weifangfirecontrolformal.weifangfirecontrolformal.support.model.RespEntity;
import com.weifangfirecontrolformal.weifangfirecontrolformal.web.service.other.UploadsService;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 测试控制器
 */
@Action
public class UploadController extends BaseController {
    protected String[] FILE_UPLOAD_IMG_EXTS = { "jpg", "png", "gif", "jpeg", "bmp", "zip","xlsx","txt","docx","doc","xls","jar", "mp4", "mp3", "pdf", "blob"};

    @Resource
    private UploadsService uploadsService;

    @RequestMapping(value = "/uploads", method = RequestMethod.POST)
    public RespEntity uploadFile(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        return uploadsService.uploadFile(params, request);
    }

    @RequestMapping(value = "/uploadsPicture", method = RequestMethod.POST)
    public RespEntity uploadsPicture(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        RespEntity respEntity = this.uploadFile(params, request);
        JSONObject jsonObject = JSONUtil.parseObj(respEntity.getData());
        String fileName = jsonObject.getStr("fileName");
        String filePath = jsonObject.getStr("filePath");
        String businessId = params.get("businessId").toString();
        jsonObject.put("businessId", businessId);
        this.uploadsService.addPicture(jsonObject);
        return respEntity;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public RespEntity add(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        String filePath = params.get("filePath").toString();
        String fileName = params.get("fileName").toString();
        String businessId = params.get("businessId").toString();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("filePath", filePath);
        jsonObject.put("fileName", fileName);
        jsonObject.put("businessId", businessId);
        RespEntity respEntity = this.uploadsService.addPicture(jsonObject);
        return respEntity;
    }

    @RequestMapping(value = "/download")
    public ResponseEntity<byte[]> downloadFile(@RequestParam("fileName") String fileName) throws IOException {
        String fileSavePath = ConfigKit.getStr("fileSavePath", "upload");
        String path = fileSavePath + fileName;
        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();
        // 下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        // 通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        // application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);

    }

    @RequestMapping(value = "/downloadExcelTemplate")
    public ResponseEntity<byte[]> downloadExcelTemplate(@RequestParam("fileName") String fileName) throws IOException {
        ClassPathResource resource = new ClassPathResource("template" + fileName);
        HttpHeaders headers = new HttpHeaders();
        // 下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        // 通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        // application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100]; // buff用于存放循环读取的临时数据
        int rc = 0;
        InputStream inputStream = resource.getInputStream();
        while ((rc = inputStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in_b = swapStream.toByteArray(); // in_b为转换之后的结果
        return new ResponseEntity<byte[]>(in_b, headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "/downloadExcel")
    public ResponseEntity<byte[]> downloadExcel(@RequestParam("fileName") String fileName) throws IOException {
        String fileSavePath = ConfigKit.getStr("excelSavePath", "excel");
        String path = fileSavePath + fileName;
        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();
        // 下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        // 通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        // application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

}
